<template>
  <div>
    <el-row :gutter="20">
      <div class="app-container">
        <el-row type="flex" justify="start" align="middle">
          <el-col :span="4"
            ><span class="el-custom-title">工序</span></el-col
          >
          <el-col :span="20" style="float:right;">
            <el-button-group style="float: right">
              <el-button
                type="primary"
                icon="el-icon-import"
                class="el-button--mini"
                @click="handleImport"
                >导入</el-button
              >
              <el-button type="primary" size="mini" @click="handleUpdate()">
                编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="ui_delete(null, null)"
              >
                删除
              </el-button>
            </el-button-group>
          </el-col>
        </el-row>
        <el-row type="flex" justify="start">
          <el-table
            v-loading="listLoading"
            :data="list"
            element-loading-text="Loading"
            border
            fit
            highlight-current-row
            @row-click="rowClick"
            @selection-change="handleSelectionChange"
            ref="dataForm"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column
              align="center"
              label="序号"
              width="95"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.id }}
              </template>
            </el-table-column>

            <el-table-column
              align="center"
              label="支线编号"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.produceProcedureBranchNo }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="支线名称"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.produceProcedureBranchName }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工序id"
              width="95"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.procedureId }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工序编号"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.procedureNo }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工序名称"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.procedureName }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="支线Id"
              width="95"
              v-if="false"
            >
              <template slot-scope="scope">
                {{ scope.row.produceProcedureBranchId }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="工段"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{ scope.row.workSectionName }}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="SOP"
              width="95"
              style="display:none;"
            >
              <template slot-scope="scope">
                {{scope.row.SOPRequirements}}
                <el-popover
                  placement="top"
                  width="400"
                  v-if="scope.row.sopId > 0"
                >
                  <div class="app-container">
                    <el-row type="flex" justify="start" align="middle">
                      工艺要求:
                    </el-row>
                    <el-row type="flex" justify="start" align="middle">
                      <span> {{scope.row.sopRequirements}} </span>
                    </el-row>
                    <el-row type="flex" justify="start" align="middle">
                      指导书:
                    </el-row>
                    <el-row type="flex" justify="start" align="middle" v-if="scope.row.attachmentFiles != null && scope.row.attachmentFiles.length>0 ">
                      <el-col  v-for='itm in scope.row.attachmentFiles.split(";")' :key=Math.round(Math.random()*1000000) >
                       <el-image v-if='(new String(itm)).indexOf("png")>0' :src=itm />
                       <video v-else width="160" height="90" src="itm" poster="http://www.youname.com/images/first.png" autoplay="autoplay"></video>
                       </el-col>
                    </el-row>
                  </div>
                  <el-button slot="reference"  >查看</el-button>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <el-row>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            :page-sizes="listQuery.pageSizes"
            @pagination="fetchData"
          />
        </el-row>
      </div>
    </el-row>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="FormSon"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="工序Id" prop="ProcedureSetId">
          <el-select-tree
            :default-expand-all="defaultExpandAll"
            :multiple="multiple"
            :placeholder="placeholder"
            :disabled="disabled"
            :data="lstAllProcedureSets"
            :props="defaultProps"
            :check-strictly="checkStrictly"
            :clearable="clearable"
            v-model="temp.ProcedureSetId"
            @change="selectChange"
            show-checks
          ></el-select-tree>
        </el-form-item>
        <el-form-item label="工序支线Id" prop="produceprocedureId">
          <el-select-tree
            :default-expand-all="defaultExpandAll"
            :multiple="multiple"
            :placeholder="placeholder"
            :disabled="disabled"
            :data="data"
            :props="defaultProps"
            :check-strictly="checkStrictly"
            :clearable="clearable"
            v-model="temp.produceprocedureId"
            @change="selectChange"
            show-checks
          ></el-select-tree>
        </el-form-item>
        <el-form-item label="序号" prop="ordered">
          <el-input-number
            v-model="temp.ordered"
            :min="1"
            :max="10"
            label="序号"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="temp.comment" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="ui_update()">
          确定
        </el-button>
      </div>
    </el-dialog>

    <mesprocedureimportchild
      :mesproduceprocedurebranchid="
        this.lstSelected != null && this.lstSelected.length > 0
          ? this.lstSelected[0].id
          : 0
      "
      :dialogVisible="this.dialogImportVisible"
      ref="dataImport"
      @childClose="closeChild"
    ></mesprocedureimportchild>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import request from "@/utils/request";
import {
  getAllSon,
  listSon,
  createSon,
  updateSon,
  deleteBatchSon,
  getTableSon,
  getAllSonByRelation
} from "@/api/procedure/mesProcedure";

import {
  getAllRelation,
  getListRelation,
  createRelation,
  createBatchRelation,
  updateRelation,
  deleteBatchRelation,
  getTableRelation as getTableSetFlow
} from "@/api/procedure/produce/mesProduceProcedureBranchProcedure";

import { getAll as getAllWorksections } from "@/api/mesWorkSection";
import ElSelectTree from "el-select-tree";
import { get } from "js-cookie";

import { getTable } from "@/api/procedure/mesProcedureSet";

import mesprocedureimportchild from "@/views/procedure/produce/mesProcedureImportChild";

export default {
  name: "mesprocedurechild",
  components: { Pagination, ElSelectTree, mesprocedureimportchild },
  data() {
    return {
      data: [],
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        pageSizes: [10, 20, 30]
      },
      curMesproduceprocedureId: 0,
      dialogFormVisible: false,
      dialogImportVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建",
        import: "导入"
      },
      rules: {
        ProcedureSetId: [
          {
            required: true,
            message: "工序Id不能为空！",
            trigger: "change"
          }
        ],
        produceprocedureId: [
          {
            required: true,
            message: "工序支线Id不能为空！",
            trigger: "change"
          }
        ],
        ordered: [
          {
            required: true,
            message: "序号不能为空！",
            trigger: "change"
          }
        ]
      },
      temp: {
        id: 0,
        ProcedureSetId: "",
        produceprocedureId: "",
        ordered: 0,
        comment: ""
      },
      tempImport: {
        workSectionId: 0,
        parentId: -1
      },
      //表格變量
      lstSelected: [],
      lstProcedureSetIds: [],
      lstWorksections: [],
      lstAllProcedureSets: [],
      displayTree: false,
      clearable: true,
      defaultExpandAll: true,
      multiple: false,
      placeholder: "请选择",
      disabled: false,
      checkStrictly: true,
      defaultProps: {
        value: "id",
        children: "children",
        label: "procedureSetName"
      }
    };
  },
  props: {
    mesproduceprocedureid: {},
    mesproduceprocedureids: {}
  },
  watch: {
    mesproduceprocedureid: function(newVale, oldValue) {
      if (newVale != null) {
        this.curMesproduceprocedureId = newVale;
      }
    },
    deep: true
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      let param = {
        page: this.listQuery.page,
        size: this.listQuery.limit
      };
      this.listLoading = true;
      getListRelation(param).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });

      //获取全部的工序组
      this.listLoading = true;
      getTable({}).then(response => {
        this.lstAllProcedureSets = response.data.children;
        this.listLoading = false;
      });
    },
    rowClick(row, column, event) {
      this.currentTherbligsTypeId = row.id;
      //this.getTherbligs()
    },
    ui_update() {
      this.$refs["FormSon"].validate(valid => {
        if (valid) {
          updateSetFlow(this.temp).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id);
            this.list.splice(index, 1, this.temp);
            this.dialogFormVisible = false;
            //通知父组件刷新
            this.$emit("refreshSteps", this.list);

            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_delete(row, index) {
      let selected = this.$refs.dataForm.selection;
      if (selected == null || selected.length == 0) {
        this.$message.error("请先选择工序");
        return;
      }
      let ids = [];
      selected.map(function(elm) {
        ids.push(elm.id);
      });
      deleteBatchRelation(ids).then(() => {
        ids.forEach(elm => {
          const index = this.list.findIndex(v => v.id === elm);
          this.list.splice(index, 1);
        });
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        ProcedureSetNo: "",
        ProcedureSetName: "",
        parentId: 0,
        workSectionId: "",
        comment: ""
      };
    },
    handleImport() {
      ;
      if (this.lstSelected == null || this.lstSelected.length == 0) {
        this.$message.error("请先选择一条工序支线");
        return;
      }
      this.dialogStatus = "import";
      this.dialogImportVisible = true;
    },
    handleUpdate() {
      let selected = this.$refs.dataForm.selection;
      if (selected == null || selected.length !== 1) {
        this.$message.error("请先选择一条工序");
        return;
      }
      this.temp = Object.assign({}, this.lstSelected[0]); // copy obj
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["FormSon"].clearValidate();
      });
    },

    selectChange() {},

    handleSelectionChange(val) {
      this.lstSelected = val;
      this.temp = Object.assign({}, cur);
    },
    closeChild(val) {
      this.dialogImportVisible = val;
    }
  }
};
</script>
<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
